import 'package:flutter/material.dart';
import 'package:flutter/cupertino.dart';
import 'network/data.dart';
import 'dart:async';
import 'dart:convert' show utf8, json;
import 'dart:io';
import 'read.dart';
import 'config.dart';


class BookBody extends StatefulWidget {

  int bookid ;

  BookBody(int bookid){
    this.bookid = bookid;
  }

  @override
  createState()=> new BookBodyState(bookid);
}

class BookBodyState extends State<BookBody>{

  int bookid;
  Map theBookinfo;

  double screenWidth;
  double screenHeight;

  BookBodyState(int bookid){
    this.bookid = bookid;
  }

  // 书籍标题
  Widget _bookTitle(String title){
    return new Text(title,textAlign: TextAlign.left,style: new TextStyle(fontSize: 18.0,fontWeight: FontWeight.bold,),);
  }
  // 书籍评分
  Widget _bookMarks(double mark,int markPeople){
    double iconSize = 15.0;

    Widget icon1;
    Widget icon2;
    Widget icon3;
    Widget icon4;
    Widget icon5;
    Color iconColor = Colors.yellow;

    if(mark <1){
      icon1 = new Icon(Icons.star_border,size: iconSize,);
    }else if(2>mark && mark>=1){
      icon1 = new Icon(Icons.star_half,size: iconSize,color: iconColor,);
    }else {
      icon1 = new Icon(Icons.star,size: iconSize,color: iconColor,);
    }

    if(mark <3){
      icon2 = new Icon(Icons.star_border,size: iconSize,);
    }else if(4>mark && mark>=3){
      icon2 = new Icon(Icons.star_half,size: iconSize,color: iconColor,);
    }else {
      icon2 = new Icon(Icons.star,size: iconSize,color: iconColor,);
    }

    if(mark <5){
      icon3 = new Icon(Icons.star_border,size: iconSize,);
    }else if(6>mark && mark>=5){
      icon3 = new Icon(Icons.star_half,size: iconSize,color: iconColor,);
    }else {
      icon3 = new Icon(Icons.star,size: iconSize,color: iconColor,);
    }

    if(mark <7){
      icon4 = new Icon(Icons.star_border,size: iconSize,);
    }else if(8>mark && mark>=7){
      icon4 = new Icon(Icons.star_half,size: iconSize,color: iconColor,);
    }else {
      icon4 = new Icon(Icons.star,size: iconSize,color: iconColor,);
    }

    if(mark <9){
      icon5 = new Icon(Icons.star_border,size: iconSize,);
    }else if(10>mark && mark>=9){
      icon5 = new Icon(Icons.star_half,size: iconSize,color: iconColor,);
    }else {
      icon5 = new Icon(Icons.star,size: iconSize,color: iconColor,);
    }
    String markText ;
    // 只做多少人评论
    if(markPeople>10000){
      double num = markPeople / 10000.0;
      num.toStringAsFixed(2);
      markText = num.toStringAsFixed(1)+"万人评";
    }


    return new Row(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: <Widget>[
        new Text(mark.toString()),
        new Row(
          children: <Widget>[
            icon1,
            icon2,
            icon3,
            icon4,
            icon5,
          ],
        ),
        new Text(markText)
      ],
    );
  }
  // 作者和分类
  Widget _authorAndCategory(String author,String category){
    return
    new Container(
      child: new Row(
        children: <Widget>[
          new GestureDetector(
            onTap: (){
              print(author);
            },
            child: new Text(author,style: new TextStyle(color: Colors.red),textAlign: TextAlign.start,),
          ),
          new Text(" | "+category),
        ],
      ),
    );
  }


  Widget _buildBookinfoSection(BuildContext context){
    print(MediaQuery.of(context).size.width);
    String name = this.theBookinfo==null?"数据出错":this.theBookinfo["name"];
    return new Row(
      mainAxisAlignment: MainAxisAlignment.start,
      crossAxisAlignment: CrossAxisAlignment.end,
      children: <Widget>[
//        new Image.asset("images/180.jpeg",
//          width: MediaQuery.of(context).size.width*0.25,
//          height: MediaQuery.of(context).size.width*0.25/3*4,
//        ),
        this.theBookinfo == null? new Image.asset("images/nosurface.jpg",
          width: MediaQuery.of(context).size.width*0.25,
          height: MediaQuery.of(context).size.width*0.25/3*4,
        ):
        new Image.network(this.theBookinfo==null?"":this.theBookinfo["surface"],
          width: MediaQuery.of(context).size.width*0.25,
          height: MediaQuery.of(context).size.width*0.25/3*4,
        ),
        new Container(
          width: MediaQuery.of(context).size.width*0.63,
          height: MediaQuery.of(context).size.width*0.25/3*4,
          padding: new EdgeInsets.only(left: 6.0),
          child: new ListView(
            itemExtent: MediaQuery.of(context).size.width*0.25/3*4/5,
            children: <Widget>[
              _bookTitle(name),
              _bookMarks(theBookinfo== null?0.0:theBookinfo["mark"],53000),
              _authorAndCategory(this.theBookinfo==null?"佚名":this.theBookinfo["author"], this.theBookinfo==null?"暂无分类":this.theBookinfo["category"]),
              new Row(
                children: <Widget>[
                  new Text('231万字'),
                  new Text(' | 已完结',)
                ],
              )
            ],
          ),
        )
      ],
    );
  }


  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    RequestData requestData = new RequestData();

    Future<String> response = requestData.baseRequest(config.baseDomain, "/api/book/"+this.bookid.toString(), "get");
    response.then((value) {
      Map data = json.decode(value);
      if(data["data"] != null){
        this.setState(() {
          this.theBookinfo = data["data"];
        });
      }
    }).catchError((err) {
      print(err);
    });
  }

  @override
  Widget build(BuildContext context) {
    print("书籍id是："+bookid.toString());
    String introduction = this.theBookinfo == null ? "暂无简介" : this.theBookinfo["introduction"];
    Widget introductionSection = new Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      mainAxisAlignment: MainAxisAlignment.start,
      mainAxisSize: MainAxisSize.max,
      children: <Widget>[
        new Text(
          '简介',
          style: new TextStyle(fontSize: 18.0),
          textAlign: TextAlign.left,
        ),
        new RichText(
          softWrap: true,
          text: new TextSpan(
            text: introduction,
            style: new TextStyle(
              color: Colors.black,
              fontSize: 14.0
            ),

          ),
        )
      ],
    );

    Widget commentSection = new Row(

    );

    Widget buttonSection =
    new Container(
      padding: new EdgeInsets.all(0.0),
      child: new Row(
        mainAxisAlignment: MainAxisAlignment.spaceEvenly,
        children: <Widget>[
          new RaisedButton(
            onPressed: (){
              screenWidth =MediaQuery.of(context).size.width;
              screenHeight = MediaQuery.of(context).size.height;
              print("点击了阅读");
              print(theBookinfo);
              if(theBookinfo["firstChapterId"]==""){
                showDialog(
                    context: context,
                    barrierDismissible: false,
                    builder: (BuildContext context) {
                      return  new AlertDialog(
                        title: new Text("服务器错误"),
                        content: new SingleChildScrollView(
                          child: new ListBody(
                            children: <Widget>[
                              new Text("服务器还没有采集该书籍")
                            ],
                          ),
                        ),
                        actions: <Widget>[
                          new FlatButton(onPressed: (){
                            Navigator.of(context).pop();
                          }, child: new Text("好的"))
                        ],
                      );
                    }
                );
              }else{
                Navigator.push(context, new MaterialPageRoute(builder: (context) => new ReadBody(this.theBookinfo["bookid"],this.theBookinfo["firstChapterId"], screenWidth, screenHeight)));
              }
            },
            child: new Text('点击阅读',style: new TextStyle(color: Colors.white),),
            color: Colors.red,
            disabledColor: Colors.grey,
          ),
          new RaisedButton(
            onPressed: (){},
            child: new Text('查看目录'),
          ),
          new RaisedButton(
            onPressed: (){

            },
            color: Colors.white,
            child: new Text('加入书架'),
            disabledColor: Colors.grey,
          ),
        ],
      ),
    );


    return new Scaffold(
      appBar: new AppBar(

      ),
      body: new ListView(
        itemExtent: 120.0,
        padding: const EdgeInsets.only(left: 10.0,right: 10.0,top: 20.0,bottom: 0.0),
        children: <Widget>[
          _buildBookinfoSection(context),
          new ListView(
            itemExtent: 70.0,
            children: <Widget>[
              buttonSection,
              introductionSection
            ],
          ),
        ],
      )
    );
  }

}
